﻿using Ebusiness_EntityFrameWork.DBContext;
using Microsoft.AspNetCore.Authorization;
using System.Net;
using System.Security.Claims;

namespace Mic.Identity.Model
{
    public class UserPermissionAuthodrizationHandler : AuthorizationHandler<UserPermissionAuthorizationRequirement>
    {
        public AppDbContext mysqlDBContext;
        public UserPermissionAuthodrizationHandler(IServiceScopeFactory  serviceScopeFactory)
        {
            using (var scope = serviceScopeFactory.CreateScope())
            {
                this.mysqlDBContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
                // 使用 dbContext 执行逻辑
            }
        }

        protected override async  Task HandleRequirementAsync(AuthorizationHandlerContext context, UserPermissionAuthorizationRequirement requirement)
        {
            #region 动态配置
            {
                ////获取用户请求的接口
                //bool bl = context.Resource is DefaultHttpContext;
                ////开始鉴权
                //if (bl == true)
                //{

                //}
                //else
                //    context.Succeed(requirement);

                IEnumerable<Claim> claimsPrincipal = context.User.Claims;
                var str = claimsPrincipal.Where(x => x.Type == "UserId").FirstOrDefault();
                if (str == null)
                {
                    context.Fail(new AuthorizationFailureReason(this, "请求失败"));
                    //var httpContext = context.Resource as HttpContext;
                    //if (httpContext != null)
                    //{
                    //    httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    //}

                    //httpContext.Response.ContentType = "application/json";
                    //var responseMessage = new { message = "Authorization failed: Custom reason" };
                    //await httpContext.Response.WriteAsJsonAsync(responseMessage);
                    return;
                }
                int UserId = int.Parse(str.Value);
                string policy = requirement.PolicyName;
                //可以将用户权限缓存到redis 或者微软扩展缓存
                List<UserPermission> userPermissions1 = mysqlDBContext.userPermissions.Where(x => x.UserID == UserId).ToList();
                DefaultHttpContext defaultHttpContext = context.Resource as DefaultHttpContext;
                string path = defaultHttpContext.Request.Path;
                if (userPermissions1.Any(x => x.PermissionName == requirement.PolicyName))
                {
                    context.Succeed(requirement);
                }
                else
                    context.Fail(new AuthorizationFailureReason(this, "请求失败"));
            }
            #endregion
        }
    }
}
